from abpy import *
from time import sleep
from MyTT import *
import akshare as ak
import numpy as np
import os
from datetime import datetime
import pymssql
from sqlalchemy import create_engine, distinct, or_, and_


######################主力跟随-价量平均线##############################

def initialize(context):
    print("初始化")
    log.info(context.current_dt)
    # print(os.getcwd())

    # 目前仅支持设置账户为股票账户，初始资金为100000，实盘中，初始资金为账户真实资金
    set_subportfolios([SubPortfolioConfig(cash=10000000, type='stock')])

    # g.security = ['110052.10', '123025.00', '123046.00', '123108.00', '123110.00',
    # '127070.00', '128033.00', '128040.00', '128053.00', '128140.00',
    # '123060.00', '118019.10', '111000.10', '110068.10', '123067.00',
    # '128015.00', '123135.00']
    g.info = {}
    g.history_data = {}
    g.close_high = {}
    g.N = 240
    g.drawback = -0.009
    g.cols = ['close', 'volume', 'high']
    g.endT = datetime.now().strftime('%Y%m%d') + '160000'
    g.account = 'KZT001'  # 账户名(跟金智投登录账户一致)
    g.buy_money = 30000  # 每只股票买入金额
    # g.amounts = 500  # 成交量
    g.atr_times = 2  # ATR倍数
    g.draw_time = 3  # 撤单等待时间
    g.minute = 59  # 最后交易分钟数
    g.pv_time = 35  # 价量平均线生效时间
    g.beg_min = 30  # 早盘(9:30以后)开始交易时间
    g.lb_period = 10  # 动态量比周期
    g.lb_value = 2.6  # 动态量比值
    g.rsi = 53  # 相对强弱rsi值
    g.max_money = 500  # 股价超过500不做
    g.money = 5e7  # 昨日成交总金额
    g.last_day_zf = 0.08  # 昨日涨幅上限
    g.last_30m_zf = 0.05  # 前一个30min最高价涨幅上限
    g.cur_df = -0.028  # 现价基于开盘价跌幅
    g.n_close = 8  # 获取8个30min收盘价
    g.ratio = 0.05  # 开盘时昨日最高价跌幅
    g.security = set()
    g.hold_stock = []  # 当前持仓股票
    g.hold_dict = {}  # 当前持仓股票信息
    g.delete_stock = set()  # 定期删除不持仓股票
    g.gold_stock = set()  # 全天每隔30min选出股票
    g.buy_stock = set()
    g.logs = []

    ####### 数据库配置信息
    # 外网地址
    g.host = '218.17.227.194'
    g.port = 10001

    # 内网地址
    #    g.host = '10.81.21.140'
    # g.port = '1433'
    g.user = 'sa'
    g.password = 'abcd1234'
    g.schema = 'dbo'
    g.db_name = 'AlphabeeCom'
    g.table_name = 'STOCK_MATCH_INFO'
    g.stocks_table = 'TrendStock'
    g.filter_stocks = get_filter_stocks()

    #  ret = get_stocks()
    # print(ret)

    g.conn = pymssql.connect(host=g.host, port=g.port, user=g.user, password=g.password, database=g.db_name)
    g.cursor = g.conn.cursor()

    dir_path = r'D:\kzz'
    file_name = 'gp.txt'
    log_name = '5min_gp_log.txt'
    file_dir = os.path.join(dir_path, file_name)
    g.log_dir = os.path.join(dir_path, log_name)

    print('主力跟随-价量平均线-new')

    pos_info = get_position_info('stock', '')
    # 当前持仓股票
    for stock_id in pos_info:
        if stock_id[:2] in ['00', '30', '60', '68', '69'] and pos_info[stock_id]['available_amout'] > 0:
            g.hold_stock.append(stock_id)

    # 查询维护用户持仓信息的表
    sql = f"select stk_code, matched_time, update_time, high from {g.table_name} where account='{g.account}'"
    g.cursor.execute(sql)
    r1 = g.cursor.fetchall()
    for item in r1:
        code = item[0]
        match_ts = item[1]
        update_ts = item[2]
        high = item[3]
        match_ts = match_ts[:match_ts.rfind(':')]
        matched_time = datetime.strptime(match_ts, '%Y%m%d %H:%M')
        update_ts = update_ts[:update_ts.rfind(':')]
        update_time = datetime.strptime(update_ts, '%Y%m%d %H:%M')

        # 如果证券成交时间不是今天，说明这部分证券是跨天交易的，要做后续追踪止损
        if matched_time.day != datetime.now().day:
            if code in g.hold_stock:
                if code in g.hold_dict:
                    if high > g.hold_dict[code]['high']:
                        g.hold_dict[code] = {'matched_time': matched_time, 'update_time': update_time, 'high': high}
                else:
                    g.hold_dict[code] = {'matched_time': matched_time, 'update_time': update_time, 'high': high}
            else:
                g.delete_stock.add(code)

    for code in g.delete_stock:
        sql = f"delete from {g.table_name} where account='{g.account}' and stk_code='{code}';"
        print('del->', sql)
        reconnect()
        g.cursor.execute(sql)
        g.conn.commit()

    for code in g.hold_dict:
        mv_data = get_history_data(code, 1, '1d', ['money', 'volume'], end_dt=g.endT)
        money = mv_data['money'][0]
        volume = mv_data['volume'][0]

        g.info[code] = {'atr_high': 0, 'drawline': money / volume}
        high_data = get_history_data(code, 10 * g.N, '1m', ['high'], end_dt=g.endT)
        update_time = g.hold_dict[code]['update_time']

        print(code)
        print(update_time)
        # print(high_data)
        # print(high_data['datetime'])

        last_time = high_data['datetime'][0]

        sql = f"update {g.table_name} set update_time = '{last_time.strftime('%Y%m%d %H:%M:%S')}' where account='{g.account}' and stk_code='{code}';"
        print('2->', sql)
        reconnect()
        g.cursor.execute(sql)
        g.conn.commit()

    # g.cursor.close()
    # g.conn.close()
    # print(g.info)
    g.security |= set(list(g.hold_dict.keys()))
    print(g.security)


def handle_data(context, data):
    log.info(context.current_dt)

    curtime = datetime.now()

    print(f'目前持仓股票：{g.hold_stock}')
    print(f'13:30选出的股票：{g.gold_stock}')

    curtime = datetime.now()

    if ((curtime.hour == 11) and (curtime.minute == 29)) or ((curtime.hour == 14) and (curtime.minute == 59)):
        with open(g.log_dir, 'w') as f:
            f.write('\n'.join(g.logs))
            f.write(50 * '-')

    try:
        get_stocks_data
    except:
        get_stocks_data = dict()

    if curtime.minute in [1, 19, 31]:
        g.gold_stock |= get_stocks()
        stocks_db = get_db_data()
        print(f'gold_stock={g.gold_stock}')
        print(f'db_stocks={stocks_db}')
        new_stocks = g.gold_stock - stocks_db

        if len(new_stocks) > 0:
            insert_stocks = [[tok[:6], int(curtime.strftime('%Y%m%d'))] for tok in new_stocks]
            print(f'insert_stocks={insert_stocks}')
            df = pd.DataFrame(insert_stocks, columns=['STK_CODE', 'DATE_T'])
            yconnect = create_engine(
                f'mssql+pymssql://{g.user}:{g.password}@{g.host}:{g.port}/{g.db_name}?charset=utf8')
            pd.io.sql.to_sql(df, g.stocks_table, yconnect, schema=g.schema, if_exists='append', index=False)

    if curtime.hour >= 10:
        g.buy_stock = g.gold_stock | get_db_data()

        g.security |= g.buy_stock

        for code in g.buy_stock:
            g.info[code] = {'order_st': 0, 'order_p': 0, 'order_qty': 0, 'order_no': 0, 'in_period': 0, 'drawline': 0,
                            'atr_high': 0, 'draw_time_count': 0, 'is_first_update': True}
            g.history_data[code] = get_history_data(code, 3 * g.N, '1m', g.cols, end_dt=g.endT)
            close_list = get_history_data(code, g.n_close, '30m', ['close'], end_dt=g.endT)
            g.close_high[code] = max(close_list['close'])

    for code in g.security:
        # 每天当时间超过14:50撤销所有委托单
        if (curtime.hour == 14) and (curtime.minute >= g.minute):
            orders = get_open_orders(security=code)
            if len(orders) > 0:
                try:
                    cancel_order(orders.order_no)
                except:
                    print(f'{code}_order_no获取不到，需手动撤单')
            else:
                print(f'{code}_orders信息获取不到')

        if (curtime.hour == 14) and (curtime.minute >= g.minute):
            continue

        atr_list = get_history_data(code, 30, '1m', ['high', 'low', 'close'], end_dt=g.endT)
        print(code)
        print(atr_list)
        print(f"atr_list['high'][0]={atr_list['high'][0]}->g.info[code]['atr_high']={g.info[code]['atr_high']}")
        atr_close_list = atr_list['close']
        atr_close_list.reverse()
        atr_close_list = np.array(atr_close_list)
        print(f"code={code}->close={atr_close_list[-1]}")
        atr_high_list = atr_list['high']
        atr_high_list.reverse()
        atr_high_list = np.array(atr_high_list)
        print(f"code={code}->high={atr_high_list[-1]}")
        atr_low_list = atr_list['low']
        atr_low_list.reverse()
        atr_low_list = np.array(atr_low_list)
        print(f"code={code}->low={atr_low_list[-1]}")
        diao_flag = 0

        if atr_list['high'][0] > g.info[code]['atr_high']:
            g.info[code]['atr_high'] = atr_list['high'][0]
            diaoding_drawline = DIAODING(atr_close_list, atr_high_list, atr_low_list, g.info[code]['atr_high'])
            diao_flag = 1

        yoyo_drawline = YOYO(atr_close_list, atr_high_list, atr_low_list)

        if (curtime.hour == 9) and (curtime.minute > g.pv_time):
            if diao_flag:
                g.info[code]['drawline'] = yoyo_drawline if yoyo_drawline > diaoding_drawline else diaoding_drawline
                print("diao_flag is true")
                print(f"code={code}->yoyo_drawline={yoyo_drawline}")
                print(f"code={code}->diaoding_drawline={diaoding_drawline}")
                print(f"code={code}->drawline={g.info[code]['drawline']}")
            else:
                g.info[code]['drawline'] = yoyo_drawline
                print(f"code={code}->yoyo_drawline={yoyo_drawline}")
                print(f"code={code}->drawline={g.info[code]['drawline']}")

        # ATR跟踪止损，平仓
        if (code in g.hold_dict) and (data[code].open > data[code].close) and (
                data[code].low < g.info[code]['drawline']):
            log_str = f"inside, time={context.current_dt}->code={code}->open={data[code].open}->close={data[code].close}->low={data[code].low}->drawline={g.info[code]['drawline']}"
            g.logs.append(log_str)
            g.info[code]['drawline'] = 0
            g.info[code]['atr_high'] = 0
            g.info[code]['order_st'] = 0
            print('z6'.center(20, '*'))
            available_amout = get_position_info('stock', code)['available_amout']
            print('z7'.center(20, '*'))
            if available_amout > 0:
                order(code, -available_amout, LimitOrderStyle(0, 10005))
                print(f"{code}止损平仓，amount={available_amout}")

        print(f'gold_stock={g.gold_stock}')

        if code in g.buy_stock:
            pre_data = get_history_data(code, 3, '1m', ['high'], end_dt=g.endT)
            current_data = get_data_last_minute(pre_data, pre_data.keys())
            if current_data['high'] > g.max_money:
                continue

            try:
                all_data = get_history_data(code, 1, '1m', ['close'], end_dt=g.endT)
                test_time = all_data['datetime'][0]
                if (curtime.year != test_time.year or curtime.month != test_time.month or curtime.day != test_time.day):
                    continue
                print(f"code={code}->all_data={all_data}")
                if len(all_data) == 0:
                    continue
            except:
                continue

            log_str2 = f"before-time={context.current_dt}->code={code}->close_len={len(g.history_data[code]['close'])}->vol_len={len(g.history_data[code]['volume'])}\n"
            print(f"code={code}->before update_data")
            update_data_res = update_data(code, g.history_data[code], g.cols, g.info[code], g.endT)
            print(f"code={code}->after update_data")
            if not update_data_res[0]:
                continue

            g.history_data[code] = update_data_res[1]
            is_high = is_over_high(g.history_data[code])

            print(f"code={code}->s1")
            # print(f"close_list={close_list[:240]}")
            # print(f"vol_list={vol_list[:240]}")

            print(f"code={code}->s2")
            pos_info = get_position_info('stock', code)
            # 30min周期内满足条件，买入
            if ((len(pos_info) > 0) and (g.info[code]['order_qty'] > 0) and (
                    0 < pos_info['available_amout'] < g.info[code]['order_qty']) or (
                        g.info[code]['order_qty'] == 0)) and is_high:
                order_qty = g.buy_money / (data[code].close + 0.01) // 100 * 100
                order_qty = 100 if order_qty == 0 else order_qty
                order_p = round(data[code].close + 0.01, 2)
                g.info[code]['order_p'] = order_p
                g.info[code]['order_qty'] = order_qty
                g.info[code]['draw_time_count'] = 1
                print(f"{code}满足下单条件，curPrice={current_data['high']}->preH={g.close_high[code]}")
                order(code, order_qty, LimitOrderStyle(0, 10015))  # 卖五价成交
                continue

                log_str = f"outside, time={context.current_dt}->code={code}->open={data[code].open}->close={data[code].close}->low={data[code].low}->drawline={g.info[code]['drawline']}"
                g.logs.append(log_str)

            print(f"code={code}->s3")

            # 委托单超多2分钟未成交，撤单
            if (len(pos_info) > 0) and (
                    (g.info[code]['order_st'] == 1) or (0 < pos_info['available_amout'] < g.info[code]['order_qty'])):
                if g.info[code]['draw_time_count'] == g.draw_time:
                    g.info[code]['drawline'] = 0
                    g.info[code]['atr_high'] = 0
                    g.info[code]['order_st'] = 0
                    g.info[code]['draw_time_count'] = 0
                    orders = get_open_orders(security=code)
                    print(orders)
                    if len(orders) > 0:
                        try:
                            cancel_order(orders.order_no)
                            print(f"{code}回撤点一半，撤单")
                        except:
                            print(f'{code}_order_no获取不到，需手动撤单')
                    else:
                        print(f'{code}_orders信息获取不到，需手动撤单')
                else:
                    g.info[code]['draw_time_count'] += 1


# 下单结果
def handle_order_ret(context, order_ret):
    log.info("order_ret", order_ret)


# 委托结果
def handle_tsu_order(context, tsu_order):
    stk_code = tsu_order.stk_code
    stk_bd = tsu_order.stkbd
    code = f'{stk_code}.{stk_bd}'
    print(f'kkk_code={code}已委托')
    g.info[code]['order_st'] = 1  # 已委托
    g.info[code]['order_no'] = tsu_order.order_no
    log.info("tsu_order", tsu_order)


# 成交结果
def handle_tsu_match(context, tsu_match):
    log.info("tsu_match", tsu_match)
    stk_code = tsu_match.stk_code
    stk_bd = tsu_match.stkbd
    code = f'{stk_code}.{stk_bd}'
    print(f'kkk_code={code}已成交')
    g.info[code]['order_st'] = 2  # 已成交

    print(f'matched_qty={tsu_match.matched_qty}->stk_biz={tsu_match.stk_biz}')
    if tsu_match.matched_qty > 0 and tsu_match.stk_biz == 100:
        sql = f"INSERT INTO {g.table_name} (account, stk_code, matched_time, update_time, matched_qty, matched_price, high) values ('{g.account}', '{tsu_match.stk_code}.{tsu_match.stkbd}', '{tsu_match.matched_date} {tsu_match.matched_time}', '{tsu_match.matched_date} {tsu_match.matched_time}',{tsu_match.matched_qty}, {tsu_match.matched_price}, {tsu_match.matched_price});"
        reconnect()
        g.cursor.execute(sql)
        print(sql)
        g.conn.commit()
        # cursor.close()
        # conn.close()


def reconnect():
    try:
        if g.cursor.connection:
           pass
    except:
        print('conneting database...')
        g.conn = pymssql.connect(host=g.host, port=g.port, user=g.user, password=g.password, database=g.db_name)
        g.cursor = g.conn.cursor()


def get_stocks():
    stocks_info = g.filter_stocks
    stocks = list()
    ls1 = list()
    ls2 = list()
    M1, M2, N = 7, 16, 120
    p1, p2 = 9, 13

    for i, item in enumerate(stocks_info):
        code = item['代码']
        fmv = item['流通股本']
        try:
            hdata = get_history_data(code, 121, '30m', ['close', 'volume'], end_dt=g.endT)
            volume = get_history_data(code, 1, '1d', ['volume'], end_dt=g.endT)['volume'][0]
        except:
            continue

        hsl = volume / fmv * 100
        close = hdata['close']
        close.reverse()
        close = np.array(close)

        vol = hdata['volume'][1:]
        vol.reverse()
        vol = np.array(vol)

        lb1 = lb(vol, p1)
        tj1 = is_lb_most(vol, M1)
        tj2 = is_lb_most(vol, M2)

        print(f'code={code}->hsl={hsl}->lb={lb1}->tj1={tj1}->tj2={tj2}')

        if (1 < hsl < 15) and (lb1 > 2.1):
            stocks.append(code)

        if not tj1:
            continue
        ls1.append(code)
        if not tj2:
            continue
        ls2.append(code)

    print(f'stocks={len(stocks)}->ls1={len(ls1)}->ls2={len(ls2)}')

    return set(stocks)


def get_filter_stocks():
    df = ak.stock_sh_a_spot_em()
    ret = df[(~df['名称'].str.contains('ST')) & (~df['名称'].str.contains('N')) & (~df['名称'].str.contains('C'))][
        ['代码', '最新价', '流通市值']]
    df = ak.stock_sz_a_spot_em()
    ret2 = df[(~df['名称'].str.contains('ST')) & (~df['名称'].str.contains('N')) & (~df['名称'].str.contains('C'))][
        ['代码', '最新价', '流通市值']]
    ret = ret.append(ret2, ignore_index=True)
    ret['代码'] = ret['代码'].map(lambda code: code + '.00' if code[:2] in ('00', '30') else code + '.10')
    ret['流通股本'] = ret['流通市值'] / ret['最新价']
    ret = ret[['代码', '流通股本']].to_dict('records')

    m, n = 3, 120
    inclose = get_history_data('399300.00', n, '1d', ['close'], end_dt=g.endT)['close']
    inclose.reverse()
    inclose = np.array(inclose)

    b1 = EMA(inclose, 1)
    bd2 = (b1 / REF(b1, m) - 1) * 100
    stocks = list()

    for i, item in enumerate(ret):
        code = item['代码']
        print(f'i={i}->code={code}')
        try:
            close = get_history_data(code, n, '1d', ['close'], end_dt=g.endT)['close']
        except:
            continue

        if len(close) < n:
            continue
        close.reverse()
        close = np.array(close)
        a1 = EMA(close, 1)
        bd1 = (a1 / REF(a1, m) - 1) * 100
        qrs = bd1 - bd2

        if (qrs[-1] <= 8) or (qrs[-2] <= 8) or (qrs[-3] <= 8):
            continue

        if close[-1] <= MA(close, 55)[-1] or close[-1] <= 5:
            continue

        if xdqr(close) < 53:
            continue

        stocks.append(item)
        # if len(stocks)>5: break

    return stocks


def get_db_data():
    dt = int(datetime.now().strftime('%Y%m%d'))
    sql = f"SELECT STK_CODE FROM TrendStock WHERE DATE_T={dt}"
    print(f"db_sql={sql}")
    reconnect()
    g.cursor.execute(sql)  # 执行sql语句
    ret = g.cursor.fetchall()  # 获取查询的所有记录
    ret = set([tok[0] + '.00' if tok[0][:2] in ('00', '30') else tok[0] + '.10' for tok in ret])

    return ret


def is_over_high(data):
    time_list = data['datetime']
    high_list = data['high']
    time_list.reverse()
    high_list.reverse()
    ct = datetime.now()

    for i in range(len(time_list)):
        if ct.day == time_list[i].day:
            idx = i
            break

    flag = high_list[-1] > max(high_list[idx:-1])

    return flag


def get_data(all_data, cols):
    t = get_current_time()
    date_list = all_data['datetime']
    # idx = date_list.index(t) if t in date_list else -1
    # idx = (idx+1) if idx==-1 else idx

    if t in date_list:
        flag = True

    res = dict()

    for col in cols:
        res[col] = all_data[col]

    return [flag, res]


def get_data_last_minute(all_data, cols):
    t = get_time()
    date_list = all_data['datetime']
    idx = 0
    flag = False
    # idx = date_list.index(t) if t in date_list else -1
    # idx = (idx+1) if idx==-1 else idx

    if t in date_list:
        flag = True
        idx = date_list.index(t)

    res = dict()

    for col in cols:
        res[col] = all_data[col][idx]

    print(f"get_data_last_minute->flag={flag}")

    return res


def update_data(code, history_data, cols, info, endT):
    t1 = history_data['datetime'][0]
    t2 = get_time()
    tf = '%Y-%m-%d %H:%M'
    flag = False
    nums = 0

    if info['is_first_update']:
        if (t1.day != t2.day):
            tlist = pd.date_range(f'{t2.year}-{t2.month}-{t2.day} {t2.hour}:{30}', t2.strftime(tf), freq='T')
            nums = 1 if len(tlist) - 1 == 0 else len(tlist) - 1
        if (t1.day == t2.day):
            nums = get_count(t1, t2)
        info['is_first_update'] = False
    else:
        if (t2.hour == 13) and (t2.minute in [0, 1]):
            nums = 5
        else:
            tlist = pd.date_range(t1.strftime(tf), t2.strftime(tf), freq='T')
            nums = len(tlist) - 1

    log_str = f"before_update_datacode={code}->time={history_data['datetime'][:5]}\n"
    print(log_str)

    if nums > 0:
        cur_data = get_history_data(code, nums + 5, '1m', cols, end_dt=endT)
        new_cols = ['datetime'] + cols
        idx = 0
        idx2 = -1

        for col in new_cols:
            item = cur_data[col]
            if (col == 'datetime') and (t2 in item):
                idx = item.index(t2)
                if t1 in item:
                    idx2 = item.index(t1)
                else:
                    idx2 = -1

                if idx2 != -1:
                    tok = item[idx: idx2]
                else:
                    tok = item[idx:]
                tok.extend(history_data[col])
                history_data[col] = tok
                flag = True
                continue
            if (col == 'datetime') and (t2 not in item):
                break
            if (col != 'datetime') and flag:
                if idx2 != -1:
                    tok = item[idx: idx2]
                else:
                    tok = item[idx:]
                tok.extend(history_data[col])
                history_data[col] = tok

    log_str = f"after_update_datacode={code}->time={history_data['datetime'][:5]}\n"
    print(log_str)

    return [flag, history_data]


def get_count(t1, t2):  # t2最新时间
    if t1.hour < 12 and t2.hour > 12:
        count = (t2.hour - t1.hour) * 60 - 90 + (t2.minute - t1.minute)
    else:
        count = (t2.hour - t1.hour) * 60 + (t2.minute - t1.minute)

    return count


def get_close_high(all_data):
    curtime = datetime.now()
    year = curtime.year
    month = curtime.month
    day = curtime.day
    hour = curtime.hour
    minute = curtime.minute

    if (hour == 9) and (30 <= minute <= 59):
        time_str = f'{year}-{month}-{day} 9:35:0'
    if (hour == 10) and (0 <= minute <= 29):
        time_str = f'{year}-{month}-{day} 10:0:0'
    if (hour == 10) and (30 <= minute <= 59):
        time_str = f'{year}-{month}-{day} 10:30:0'
    if (hour == 11) and (0 <= minute <= 29):
        time_str = f'{year}-{month}-{day} 11:0:0'
    if (hour == 13) and (0 <= minute <= 29):
        time_str = f'{year}-{month}-{day} 13:5:0'
    if (hour == 13) and (30 <= minute <= 59):
        time_str = f'{year}-{month}-{day} 13:30:0'
    if (hour == 14) and (0 <= minute <= 29):
        time_str = f'{year}-{month}-{day} 14:0:0'
    if (hour == 14) and (30 <= minute <= 59):
        time_str = f'{year}-{month}-{day} 14:30:0'

    t = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')

    if t in all_data['datetime']:
        idx = all_data['datetime'].index(t)
        if ((hour == 9) and (30 <= minute <= 59)) or ((hour == 13) and (0 <= minute <= 29)):
            idx += 1
    else:
        idx = 0

    close_list = all_data['close'][idx: idx + 6]

    return max(close_list)


def get_time():
    curtime = datetime.now()
    year = curtime.year
    month = curtime.month
    day = curtime.day
    hour = curtime.hour
    minute = curtime.minute

    t = datetime.strptime(f'{year}-{month}-{day} {hour}:{minute}:0', '%Y-%m-%d %H:%M:%S')
    return t


def get_current_time():
    curtime = datetime.now()
    year = curtime.year
    month = curtime.month
    day = curtime.day
    hour = curtime.hour
    minute = curtime.minute
    flag = False
    ch = 9
    cm = 0

    if (hour == 9) and (30 <= minute <= 59):
        ch = 10
        cm = 0
    if (hour == 10) and (0 <= minute <= 29):
        ch = 10
        cm = 30
    if (hour == 10) and (30 <= minute <= 59):
        ch = 11
        cm = 0
    if (hour == 11) and (0 <= minute <= 30):
        ch = 11
        cm = 30
    if (hour == 13) and (0 <= minute <= 29):
        ch = 13
        cm = 30
    if (hour == 13) and (30 <= minute <= 59):
        ch = 14
        cm = 0
    if (hour == 14) and (0 <= minute <= 29):
        ch = 14
        cm = 30
    if (hour == 14) and (30 <= minute <= 59):
        ch = 15
        cm = 0

    t = datetime.strptime(f'{year}-{month}-{day} {ch}:{cm}:0', '%Y-%m-%d %H:%M:%S')

    return t


def xdqr(close):
    N = 55
    p1 = np.maximum(close - REF(close, 1), 0)
    p1[p1 == 0] = 1
    p2 = abs(close - REF(close, 1))
    p2[p2 == 0] = 1
    v1 = SMA(p1, N, 1)
    v2 = SMA(p2, N, 1)
    res = v1[N:] / v2[N:] * 100
    rsi = EMA(res, 3)

    return rsi[-1]


def lb(vol, n):
    B1 = MA(vol, n)
    B1[B1 == 0] = 1
    val = vol[n:] / B1[n:]

    return val[-1]


def is_lb_most(vol_list, lb_period):
    B1 = MA(vol_list, lb_period)
    B1[B1 == 0] = 1
    lb_list = vol_list[-8:] / B1[-8:]
    flag = lb_list[-1] >= max(lb_list[:-1])

    return flag


def my_atr(close, high, low):
    tr = max((high - low), abs(close - high), abs(close - low))

    return tr


def YOYO(close_list, high_list, low_list, N=20):
    atr = ATR(close_list, high_list, low_list, N=N)[-1]
    drawline = close_list[-1] - 1.5 * atr

    return drawline


def DIAODING(close_list, high_list, low_list, high, N=20):
    atr = ATR(close_list, high_list, low_list, N=N)[-1]
    drawline = high - 3 * atr

    return drawline
